package com.lanxiaoye.shoppingSystem.common;

import com.lanxiaoye.shoppingSystem.common.exception.BaseException;
import com.lanxiaoye.shoppingSystem.common.exception.EmptyException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

/**
 * Created by libing on 2016/12/13.
 */
public class EncryptUtil {
    public static final String KEY_ALGORITHM = "DES";
    public static final String CIPHER_ALGORITHM = "DES/ECB/NoPadding";

    /**
     *
     * 生成密钥key对象
     * @param keyStr 密钥字符串
     * @return 密钥对象
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws Exception
     */
    private static SecretKey keyGenerator(String keyStr) throws EmptyException, BaseException {
        try {
            if (keyStr == null)
                throw new EmptyException("[EncryptUtil][keyGenerator] keyStr empty");
            byte[] input = HexString2Bytes(keyStr);
            DESKeySpec desKeySpec = new DESKeySpec(input);
            //创建一个密钥工厂，然后把它DESKEYSpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            return secretKey;
        }catch (EmptyException ee){
            throw new EmptyException(ee.getMessage());
        }catch (InvalidKeyException e){
            throw new BaseException("[EncryptUtil][keyGenerator] exception: "+e.getMessage());
        }catch (NoSuchAlgorithmException e){
            throw new BaseException("[EncryptUtil][keyGenerator] exception: "+e.getMessage());
        }catch (InvalidKeySpecException e){
            throw new BaseException("[EncryptUtil][keyGenerator] exception: "+e.getMessage());
        }catch (Exception e){
            throw new BaseException("[EncryptUtil][keyGenerator] exception: "+e.getMessage());
        }
    }

    //从十六进制字符串到字节数组的转换
    public static byte[] HexString2Bytes(String hexStr) throws EmptyException, BaseException {
        try {
            if (hexStr == null)
                throw new EmptyException("[EncryptUtil][HexString2Bytes] hexStr empty");
            byte[] b = new byte[hexStr.length() / 2];
            int j = 0;
            for (int i = 0; i < b.length; i++) {
                char c0 = hexStr.charAt(j++);
                char c1 = hexStr.charAt(j++);
                b[i] = (byte) ((parse(c0) << 4) | parse(c1));
            }
            return b;
        } catch (EmptyException ee) {
            throw new EmptyException(ee.getMessage());
        } catch (Exception e) {
            throw new BaseException("[EncryptUtil][HexString2Bytes] exception: "+e.getMessage());
        }
    }

    private static int parse(char c) throws BaseException {
        //0x0f = 15d ,写成0f而不是0xf是为了表示数据长度为两字节(8位).
        try {
            if (c >= 'a') return (c - 'a' + 10) & 0x0f;
            if (c >= 'A') return (c - 'A' + 10) & 0x0f;
            return (c - '0') & 0x0f;
        }catch (Exception e){
            throw new BaseException("[EncryptUtil][parse] exception: "+e.getMessage());
        }
    }

    /**
     * 加密数据
     * @param data 待加密数据
     * @param key 密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data,String key)throws EmptyException, BaseException {
        try {
            if (data == null)
                throw new EmptyException("[EncryptUtil][encrypt]  data empty");
            if (key == null)
                throw new EmptyException("[EncryptUtil][encrypt]  key empty");
            Key desKey = keyGenerator(key);
            //实例化Clipher对象，它用于完成实际的加密操作
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            SecureRandom random = new SecureRandom();
            //初始化Cipher对象，设置为加密模式
            cipher.init(Cipher.ENCRYPT_MODE, desKey, random);
            byte[] results = cipher.doFinal(data.getBytes());
            //执行加密操作，加密后的结果通常都会用Base64编码进行传输
            return Base64.encodeBase64String(results);
        }catch (EmptyException ee){
            throw new EmptyException(ee.getMessage());
        }catch (Exception e){
            throw new BaseException("[EncryptUtil][encrypt] exception: "+e.getMessage());
        }
    }

    /**
     * 解密数据
     * @param data 待解密数据
     * @param key 密钥
     * @return 解密后的数据
     */
    public static String decrypt(String data,String key) throws EmptyException, BaseException {
        try {
            if (data == null)
                throw new EmptyException("[EncryptUtil][decrypt]  data empty");
            if (key == null)
                throw new EmptyException("[EncryptUtil][decrypt]  key empty");
            Key desKey = keyGenerator(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            //执行解密操作
            return new String(cipher.doFinal(Base64.decodeBase64(data)));
        }catch (EmptyException ee){
            throw new EmptyException(ee.getMessage());
        }catch (Exception e){
            throw new BaseException("[EncryptUtil][decrypt]exception: "+e.getMessage());
        }
    }


    public static String SHA1(String decript) throws BaseException, EmptyException {
        try {
            if (decript == null)
                throw new EmptyException("[EncryptUtil][SHA1] decript empty");
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new BaseException("[EncryptUtil][SHA1] exception: "+e.getMessage());
        } catch (EmptyException e) {
            throw new EmptyException(e.getMessage());
        } catch (Exception e) {
            throw new BaseException("[EncryptUtil][SHA1] exception: "+e.getMessage());
        }
    }

}
